package com.dnjn.happiness.emo.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.dnjn.happiness.common.amqp.AmqpSender;
import com.dnjn.happiness.common.config.ThreadPoolConfig;
import com.dnjn.happiness.common.config.ext.SpringContextHolder;
import com.dnjn.happiness.common.core.constant.Constants;
import com.dnjn.happiness.common.core.constant.HappyConstants;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.emo.api.domain.UserHcmQxPtdata;
import com.dnjn.happiness.emo.api.domain.UserHcmQxPtdataBean;
import com.dnjn.happiness.common.core.score.vo.HappyUserHcmQxPtData;
import com.dnjn.happiness.common.core.score.vo.HappyVO;
import com.dnjn.happiness.emo.domain.EmoUserRecordPos;
import com.dnjn.happiness.emo.service.IEmoUserRecordPosService;
import com.dnjn.happiness.emo.service.IUserHcmQxPtdataService;
import com.dnjn.happiness.emo.webapi.c3v8.in.PosRecordIn;
import com.dnjn.happiness.emo.webapi.c3v8.out.C3v8Out;
import com.dnjn.happiness.emo.webapi.hcm.HCM_SAPHRClient;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Component("webApiHandler")
public class WebApiHandler {

    @Autowired
    private IEmoUserRecordPosService emoUserRecordPosService;

    @Autowired
    private IUserHcmQxPtdataService userHcmQxPtdataService;

    @Autowired
    private RemoteUserService userService;

    



    private static final Logger log = LoggerFactory.getLogger(WebApiHandler.class);

    public void insertYesterdayPosRecord(){
        //根据用户分段查询
        Long totalCount = 0L;
        R<Long> result = userService.getUserCount(SecurityConstants.INNER);
        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
            totalCount = result.getData();
        }
        final int runSize = 10;
        final int pageSize = 1000;
        final int pageCount = totalCount % pageSize == 0 ? totalCount.intValue() / pageSize : totalCount.intValue() / pageSize + 1;//87
        ThreadPoolExecutor executor = ThreadPoolConfig.createThread(runSize);
        // 计算sql语句中每个分页查询的起始和结束数据下标
        for (int i = 0; i < pageCount; i++) {
            Integer page =  i * pageSize ;
            executor.execute(()->{
                log.info("每次查询的下标:" + page + ",条数:" + pageSize);
                List<SysUser> userList = new ArrayList<>();
                R<List<SysUser>> listResut = userService.selectByLimit(page, pageSize, SecurityConstants.INNER);
                if (StringUtils.isNotNull(listResut) && StringUtils.isNotNull(listResut.getData())){
                    userList = listResut.getData();
                }
                insertPosRecord(userList);
            });
        }
        executor.shutdown();
    }

    private void insertPosRecord(List<SysUser> userListAll) {
        //根据工号去查询
        String yesterday = LocalDate.now().minusDays(1).toString();
        PosRecordIn posRecordIn = new PosRecordIn()
                .setStartTime(yesterday + " 00:00:00")
                .setEndTime(yesterday + " 23:59:59")
                .setSecId(0);
        posRecordIn.setPageSize(1000);
        for (SysUser user : userListAll) {
            String empno = user.getEmpno();
            if (StringUtils.isNotEmpty(empno)){
                posRecordIn.setPageIndex(1);
                posRecordIn.setEmpNo(empno);
                C3v8Out<Object> posRes = posRecordIn.send();
                if (Objects.isNull(posRes)){
                    log.error("调用消费接口失败==============");
                    return;
                }
                if (!posRes.getCode().equals(0) || Objects.isNull(posRes.getData()) ||
                        CollectionUtils.isEmpty(posRes.getData().getDatalist()) || posRes.getData().getTotalCount().equals(0)){
                    continue;
                }else {
                    for (Object obj : posRes.getData().getDatalist()) {
                        //落库
//                        EmoUserRecordPos pos = new ObjectMapper().convertValue(obj, EmoUserRecordPos.class);
                        EmoUserRecordPos pos = JSON.parseObject(JSON.toJSONString(obj), EmoUserRecordPos.class);
                        pos.setUserId(user.getUserId());
                        pos.setEmpno(user.getEmpno());
                        emoUserRecordPosService.insert(pos);
                    }
                    Integer pageCount = posRes.getData().getPageCount();
                    if (pageCount > 1){
                        int INDEX = 2;
                        for (Integer i = 0; i < pageCount; i++) {
                            posRecordIn.setPageIndex(INDEX);
                            C3v8Out<Object> res = posRecordIn.send();
                            List<Object> dataList = res.getData().getDatalist();
                            for (Object obj : dataList) {
                                //落库
                                EmoUserRecordPos pos = JSON.parseObject(JSON.toJSONString(obj), EmoUserRecordPos.class);
                                pos.setUserId(user.getUserId());
                                pos.setEmpno(user.getEmpno());
                                emoUserRecordPosService.insert(pos);
                            }
                            INDEX++;
                        }
                    }
                }
            }
        }
    }

    public void insertYesterdayUserHcmQxPtdataRecord() {
        String host = getEnv("hcm.host");;
        final LocalDate startDate = LocalDate.now().minusDays(1);
        final LocalDate endDate = LocalDate.now();

        String resp = null;
        try {
            String userHcmQxPtdataKey = getEnv("hcm.key");
            String userHcmQxPtdataSercet = getEnv("hcm.sercet");

            resp = HCM_SAPHRClient.loadQxPtData(host, startDate, endDate,userHcmQxPtdataKey,userHcmQxPtdataSercet);
            log.info("消费接口信息返回resp===========" + resp);
            UserHcmQxPtdataBean bean = JSON.parseObject(resp, new TypeReference<UserHcmQxPtdataBean>() {});
            if (!CollectionUtils.isEmpty(bean.getT_QJ())){
                List<UserHcmQxPtdata> list = new ArrayList<>();
                for (UserHcmQxPtdataBean.TQJ tqj : bean.getT_QJ()) {
                    UserHcmQxPtdata dto = new UserHcmQxPtdata();
                    dto.setEmpno(tqj.getZWORKCODE())
                            .setDataType(Constants.TQJ)
                            .setPersonNum(tqj.getPersonNum())
                            .setAwart(tqj.getAwart())
                            .setAtext(tqj.getAtext())
                            .setStartDate(tqj.getStartDate())
                            .setEndDate(tqj.getEndDate())
                            .setBeginTime(tqj.getBeginTime())
                            .setEndTime(tqj.getEndTime())
                            .setLeaveTime(tqj.getLeaveTime());
//                    userHcmQxPtdataService.save(dto);
                    list.add(dto);
                }
                userHcmQxPtdataService.saveBatch(list);
            }
            if (!CollectionUtils.isEmpty(bean.getT_YC())){
                List<UserHcmQxPtdata> list = new ArrayList<>();
                for (UserHcmQxPtdataBean.TYC tyc : bean.getT_YC()) {
                    UserHcmQxPtdata dto = new UserHcmQxPtdata();
                    dto.setEmpno(tyc.getEmpno())
                            .setDataType(Constants.TYC)
                            .setPersonNum(tyc.getPersonNum())
                            .setCheckDate(tyc.getCheckDate())
                            .setBelateCount(tyc.getBelateCount())
                            .setEarlyCount(tyc.getEarlyCount())
                            .setAbsenceCount(tyc.getAbsenceCount())
                            .setMakeupCount(tyc.getMakeupCount());
//                    userHcmQxPtdataService.save(dto);
                    list.add(dto);
                }
                userHcmQxPtdataService.saveBatch(list);

//                  todo 考勤落库之后 发mq
                List<String> empnoList = list.stream().map((item) -> item.getEmpno()).collect(Collectors.toList());
                empnoList.stream().forEach(item->{
                    Long userId = null;
                    R<SysUser> result = userService.getUserByEmpno(item, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
                        userId = result.getData().getUserId();
                    }
                    HappyVO happyVO = new HappyVO();
                    happyVO.setUserId(userId);
                    happyVO.setRtype(HappyConstants.EMO_USER_RTYPE_ATTENDANCE);
                    HappyUserHcmQxPtData happyUserHcmQxPtData = new HappyUserHcmQxPtData();
                    happyUserHcmQxPtData.setCount(1);
                    happyVO.setUserHcmQxPtData(happyUserHcmQxPtData);

                    AmqpSender.sendArgs(happyVO);
                });


            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("查询考勤接口记录失败：" + e);
        }
    }


    private static String getEnv(String key) {
        try {
            return SpringContextHolder.getContext().getEnvironment().getProperty(key);
        } catch (Exception e) {
            log.warn(String.format("[warn] %s %s; config [%s] first!", e.getMessage(), e.getClass().getCanonicalName(), key));
        }
        return null;

    }



}


